﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using PaulBeck.Timesheet.BOL;

namespace PaulBeck.Timesheet.WebParts.BookTimeItem
{
    public partial class BookTimeItemUserControl : UserControl
    {

        #region "Properties"

        public int WeekId
        {
            get
            {
                object o = ViewState["WeekId"];
                return (o == null) ? 0 : (int)o;
            }
            set
            {
                ViewState["WeekId"] = value;
            }
        }

        public int UserId
        {
            get
            {
                object o = ViewState["UserId"];
                return (o == null) ? 0 : (int)o;
            }
            set
            {
                ViewState["UserId"] = value;
            }
        }

        #endregion

        #region "Control Events"

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int rptid = Convert.ToInt32(Page.Request.QueryString["rptid"]);
                int dayId = 0;
                int projectid = 0;
                double time = 0;
                if (rptid > 0)
                {  // Update the record
                    btnInsert.Visible = false;
                    btnUpdate.Visible = true;
                    btnDelete.Visible = true;

                    BookTimeItemResourceProject resource = BookTimeItemBOL.BookTimeItemGetResource(rptid);
                    txtNotes.Text = resource.Notes;
                    dayId = (int)resource.DayId;
                    projectid = resource.ProjectId;
                    time = (double)resource.Time;
                    UserId = resource.ResourceId;
                }
                else
                {   // Insert a new ResourceProjectTime item
                    btnInsert.Visible = true;
                    btnUpdate.Visible = false;
                    btnDelete.Visible = false;
                }

                string loginName = CommonWFE.CurrentUserName();
                if (UserId == 0)
                {
                    UserId = Convert.ToInt32(Page.Request.QueryString["userid"]);
                }
                if (UserId == 0)   // If userid not found by edit rptid then checked querystring, lastly revert to current user 
                {
                    // Display the current consultant/resource/user
                    UserId = BOL.BookTimeItemBOL.BookTimeItemGetResourceId(loginName);                   
                }

                WeekId = Convert.ToInt32(Page.Request.QueryString["weekid"]);
                var days = BookTimeItemBOL.BookTimeItemGetResourceDays(WeekId);
                int i = 0;
                foreach (var item in days)
                {
                    ddlDay.Items.Add(new ListItem(String.Format("{0:ddd, MMM d, yyyy}", item.DayDate), item.DayEntryId.ToString()));
                    if (dayId != 0)
                    {
                        if (dayId == item.DayEntryId)
                        {
                            ddlDay.SelectedIndex = i;
                        }
                    }
                    i++;
                }
                if (dayId == 0)
                {
                    ddlDay.SelectedIndex = 2;  // Make monday the default if day is unknown i.e. new item
                }

                var projects = BookTimeItemBOL.BookTimeItemGetProjectInfo(UserId);
                ListItemCollection lic = new ListItemCollection();
                int iPrj = 0;
                foreach (var prjItem in projects)
                {
                    ddlProject.Items.Add(new ListItem(prjItem.ProjectDescription, prjItem.ProjectResourceId.ToString()));
                    if (prjItem.ProjectId == projectid)
                    {
                        ddlProject.SelectedIndex = iPrj;
                    }
                    iPrj++;
                }

                int iTime = 0;
                if (time == 0)   // New item/Insert, set the default time
                {
                    time = CommonWFE.GetTimesheetWorkDayLength();
                }
                foreach (ListItem li in ddlTime.Items)
                {
                    if (Convert.ToDouble(li.Value) == time)
                    {
                        ddlTime.SelectedIndex = iTime;
                    }
                    iTime++;
                }

                BOL.Status weekStatus = BOL.Common.GetWeekStatus(WeekId);
                if ((weekStatus == BOL.Status.Approved) || (weekStatus == BOL.Status.Submitted))
                {
                    pnlData.Enabled = false;
                }
            }
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            string loginName = CommonWFE.CurrentUserName();
            ResourceProjectTime rpt = BOL.BookTimeItemBOL.BookTimeItemInsert(loginName, Convert.ToInt32(ddlDay.SelectedValue), txtNotes.Text, Convert.ToInt32(ddlProject.SelectedValue), Convert.ToDouble(ddlTime.SelectedValue));
            // Update the Day Time column total
            UpdateDayTime((int)rpt.DayEntryIdFk, rpt.ProjectResourceId);
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int rptid = Convert.ToInt32(Page.Request.QueryString["rptid"]);
            ResourceProjectTime rpt = BOL.BookTimeItemBOL.BookTimeItemUpdate(rptid, txtNotes.Text, Convert.ToInt32(ddlDay.SelectedValue), Convert.ToInt32(ddlProject.SelectedValue), Convert.ToDouble(ddlTime.SelectedValue));
            // Update the Day Time column total
            UpdateDayTime((int)rpt.DayEntryIdFk, rpt.ProjectResourceId);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int rptid = Convert.ToInt32(Page.Request.QueryString["rptid"]);
            ResourceProjectTime rpt = BOL.BookTimeItemBOL.BookTimeItemDelete(rptid);
            // Update the Day Time column total
            UpdateDayTime((int)rpt.DayEntryIdFk, rpt.ProjectResourceId);
        }

        #endregion

        #region "Private Methods"

        /// <summary>
        /// Update the Day Time column total
        /// </summary>
        /// <param name="dayEntryIdFk"></param>
        /// <param name="projectResourceId"></param>
        private void UpdateDayTime(int dayEntryIdFk, int projectResourceId)
        {
            BOL.BookTimeItemBOL.UpdateDayTime(dayEntryIdFk);
            BOL.BookTimeItemBOL.UpdateProjectResourceTime(projectResourceId);
            Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            Context.Response.Flush();
            Context.Response.End();
        }

        #endregion

    }
}
